<template>
  <div class="page-container">
    <el-card class="address-card">
      <template #header>
        <div class="card-header">
          <h3>收货地址</h3>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加地址
          </el-button>
        </div>
      </template>
      
      <!-- 地址列表 -->
      <div class="address-list" v-if="addresses.length > 0">
        <div
          v-for="(address, index) in addresses"
          :key="index"
          class="address-item"
          :class="{ 'is-default': address.isDefault }"
        >
          <div class="address-content">
            <div class="address-info">
              <div class="contact-info">
                <span class="name">{{ address.name }}</span>
                <span class="phone">{{ address.phone }}</span>
                <el-tag v-if="address.isDefault" type="success" size="small">默认</el-tag>
              </div>
              <div class="address-detail">
                {{ address.detail }}
              </div>
            </div>
            <div class="address-actions">
              <el-button
                v-if="!address.isDefault"
                type="text"
                size="small"
                @click="setDefaultAddressHandler(index)"
              >
                设为默认
              </el-button>
              <el-button type="text" size="small" @click="editAddress(index)">
                编辑
              </el-button>
              <el-button type="text" size="small" @click="deleteAddressHandler(index)" class="delete-btn">
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <el-empty
        v-else
        description="暂无收货地址"
        :image-size="120"
      >
        <el-button type="primary" @click="showAddDialog">添加地址</el-button>
      </el-empty>
    </el-card>
    
    <!-- 添加/编辑地址对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑地址' : '添加地址'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addressFormRef"
        :model="addressForm"
        :rules="addressRules"
        label-width="80px"
      >
        <el-form-item label="收货人" prop="name">
          <el-input v-model="addressForm.name" placeholder="请输入收货人姓名" />
        </el-form-item>
        
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        
        <el-form-item label="详细地址" prop="detail">
          <el-input
            v-model="addressForm.detail"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址"
          />
        </el-form-item>
        
        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAddress" :loading="saving">
            {{ isEditing ? '保存' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getAddresses, addAddress, updateAddress, deleteAddress, setDefaultAddress } from '../../api/address'

const addresses = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const isEditing = ref(false)
const editingIndex = ref(-1)
const saving = ref(false)

const addressFormRef = ref()

const addressForm = reactive({
  name: '',
  phone: '',
  detail: '',
  isDefault: false
})

const addressRules = {
  name: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  detail: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '详细地址长度在 5 到 100 个字符', trigger: 'blur' }
  ]
}

// 加载地址列表
const loadAddresses = async () => {
  loading.value = true
  try {
    const response = await getAddresses()
    addresses.value = response.data || []
  } catch (error) {
    console.error('加载地址列表失败:', error)
    ElMessage.error('加载地址列表失败')
  } finally {
    loading.value = false
  }
}

// 显示添加对话框
const showAddDialog = () => {
  resetForm()
  isEditing.value = false
  dialogVisible.value = true
}

// 编辑地址
const editAddress = (index) => {
  const address = addresses.value[index]
  editingIndex.value = index
  isEditing.value = true
  
  // 填充表单
  addressForm.name = address.name
  addressForm.phone = address.phone
  addressForm.detail = address.detail
  addressForm.isDefault = address.isDefault
  
  dialogVisible.value = true
}

// 保存地址
const saveAddress = async () => {
  if (!addressFormRef.value) return
  
  const valid = await addressFormRef.value.validate().catch(() => false)
  if (!valid) return
  
  saving.value = true
  try {
    const addressData = {
      name: addressForm.name,
      phone: addressForm.phone,
      detail: addressForm.detail,
      isDefault: addressForm.isDefault
    }
    
    if (isEditing.value) {
      const address = addresses.value[editingIndex.value]
      await updateAddress(address.id, addressData)
      ElMessage.success('地址更新成功')
    } else {
      await addAddress(addressData)
      ElMessage.success('地址添加成功')
    }
    
    dialogVisible.value = false
    await loadAddresses()
  } catch (error) {
    console.error('保存地址失败:', error)
    ElMessage.error('保存地址失败')
  } finally {
    saving.value = false
  }
}

// 设置默认地址
const setDefaultAddressHandler = async (index) => {
  try {
    const address = addresses.value[index]
    await setDefaultAddress(address.id)
    ElMessage.success('默认地址设置成功')
    await loadAddresses()
  } catch (error) {
    console.error('设置默认地址失败:', error)
    ElMessage.error('设置默认地址失败')
  }
}

// 删除地址
const deleteAddressHandler = async (index) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个地址吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const address = addresses.value[index]
    await deleteAddress(address.id)
    ElMessage.success('地址删除成功')
    await loadAddresses()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除地址失败:', error)
      ElMessage.error('删除地址失败')
    }
  }
}

// 重置表单
const resetForm = () => {
  addressForm.name = ''
  addressForm.phone = ''
  addressForm.detail = ''
  addressForm.isDefault = false
  editingIndex.value = -1
  
  if (addressFormRef.value) {
    addressFormRef.value.clearValidate()
  }
}

onMounted(() => {
  loadAddresses()
})
</script>

<style scoped>
.page-container {
  padding: 0;
  background: #f0f2f5;
  min-height: calc(100vh - 60px);
  width: 100%;
  margin: 0;
  box-sizing: border-box;
}

.address-card {
  margin: 24px;
  margin-bottom: 24px;
}

.address-card {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
}

.address-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.address-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  transition: all 0.3s ease;
}

.address-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.address-item.is-default {
  border-color: #67c23a;
  background: #f0f9ff;
}

.address-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.address-info {
  flex: 1;
}

.contact-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.contact-info .name {
  font-weight: 600;
  color: #303133;
  font-size: 16px;
}

.contact-info .phone {
  color: #606266;
  font-size: 14px;
}

.address-detail {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.address-actions {
  display: flex;
  gap: 8px;
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  color: #f78989;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .address-content {
    flex-direction: column;
    gap: 12px;
  }
  
  .address-actions {
    justify-content: flex-end;
  }
}
</style>
